﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using WebApplication.Core.Helpers;

namespace WebApplication.Core
{
    public class Builder
    {
        public void BuildApplication(string csProj, string parameters, string serverName, string applicationName)
        {
            string dir = Path.GetTempPath() + serverName + "(" + applicationName + ")";
            if (Directory.Exists(dir))
                Directory.Delete(dir, true);
            Directory.CreateDirectory(dir);
            if (string.IsNullOrEmpty(parameters))
            {
                parameters = "/t:Package";
            }
            if(!parameters.Contains("OutputPath"))
            {
                parameters += " /p:OutputPath=" + dir;
            }
            string srcPath =  AppSettingsHelper.GetSrcPath + serverName + "(" + applicationName + ")";
            string csProjPath = string.Empty;
            csProjPath = Directory.GetFiles(srcPath, csProj, SearchOption.AllDirectories).FirstOrDefault();
            if (string.IsNullOrEmpty(csProjPath))
                throw new InvalidOperationException("Не найден файл для компиляции.");
            string path = AppSettingsHelper.GetMsBuildPath;
            string batCmd = string.Format("\"{0}MsBuild.exe\" {1} {2}", path, csProjPath, parameters);
            //компиляция
            CmdHelper.RunCmd(batCmd, false);
        }
    }
}